package zhai.docking.alipay.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import zhai.docking.alipay.constant.ResultConstant;
import zhai.docking.alipay.domain.base.common.Result;
import zhai.docking.alipay.service.biz.AlipayImgSer;
import zhai.docking.alipay.util.FileUtil;
import zhai.docking.alipay.util.StringUtil;

/**
 * @author Created by 翟凤玺
 * @package zhai.docking.alipay.api
 * @project-name zhai-docking-alipay
 * @description 支付宝-图片-api
 * @create-datetime 2021/1/22 13:33
 */
@RestController
@RequestMapping("/api/alipay/img")
@Api("支付宝-图片-api")
public class AlipayImgCtr {

    @Autowired
    AlipayImgSer alipayImgSer;

    @RequestMapping(path = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "支付宝图片上传", notes = "支付宝图片上传", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity upload(@RequestParam(name = "file") MultipartFile file) {
        /** 校验：是否为空 */
        if (file.isEmpty()) {
            return ResponseEntity.ok(Result.failure(ResultConstant.FAIL_SYS_NO_IN_ERROR_CODE, ResultConstant.FAIL_SYS_NO_IN_ERROR_MSG));
        }
        /** 校验：文件类型 */
        String fileType = FileUtil.getFileType(FileUtil.getFileName(file));
        if (StringUtil.isBlank(fileType)) {
            return ResponseEntity.ok(Result.failure(ResultConstant.FAIL_SYS_DEF_CODE, "该文件没有文件类型"));
        }
        if (!FileUtil.isFileType(fileType, FileUtil.FILE_TYPE_JPG, FileUtil.FILE_TYPE_JPEG)) {
            return ResponseEntity.ok(Result.failure(ResultConstant.FAIL_BIZ_DEF_CODE, StringUtil.join("不支持上传该文件格式：", fileType)));
        }
        /** 校验：文件大小 */
        boolean minSize = FileUtil.checkMinSize(file.getSize(), 50, FileUtil.UNIT_KB);
        if (!minSize) {
            return ResponseEntity.ok(Result.failure(ResultConstant.FAIL_BIZ_DEF_CODE, "文件大小不能小于50KB"));
        }
        boolean maxSize = FileUtil.checkMaxSize(file.getSize(), 5, FileUtil.UNIT_MB);
        if (!maxSize) {
            return ResponseEntity.ok(Result.failure(ResultConstant.FAIL_BIZ_DEF_CODE, "文件大小不能大于5MB"));
        }
        Result result = alipayImgSer.upload(file);
        return ResponseEntity.ok().body(result);
    }
}